﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using System.Windows.Media.Imaging;

namespace imaginecup
{
    public class PhotoNote
    {
        int bitmapindex;
        bool visible;

        public int BitMapIndex
        {
            set { bitmapindex = value; }
            get { return bitmapindex; }
        }

        public bool Visible
        {
            set { visible = value; }
            get { return visible; }
        }
    }

    public partial class ShowPhoto : UserControl
    {
        //当前地图的控制范围
        private double east, west, north, south;        
        //当前照片的下标
        private int curindex = -1;
        //照片是否载入完毕
        private bool isLoaded = false;
        //9个在列表中的图片
        private PhotoNote[] photohead = new PhotoNote[9];
        //从文件名到下标的映射
        private Dictionary<string, int> namevalue;
        
        //图片的根地址
        private string uriprefix = "http://localhost:1276/photo/";

        private Image curmain;
        private Image mousedown;
        //服务器端的服务
        private ServiceReference1.DataProviderSoapClient getphotoclient = new imaginecup.ServiceReference1.DataProviderSoapClient();
        //照片的列表
        private List<ServiceReference1.CPhoto> photolist;

        /// <summary>
        /// 构造函数，需要指点范围
        /// </summary>
        /// <param name="e"></param>
        /// <param name="w"></param>
        /// <param name="n"></param>
        /// <param name="s"></param>
        public ShowPhoto(double e,double w,double n,double s)
        {
            InitializeComponent();
            east = e;
            west = w;
            north = n;
            south = s;
            this.Loaded += new RoutedEventHandler(ShowPhoto_Loaded);
        }

        /// <summary>
        /// 此控件被加载时的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ShowPhoto_Loaded(object sender, RoutedEventArgs e)
        {
            //添加事件
            getphotoclient.getPhotoCompleted += new EventHandler<imaginecup.ServiceReference1.getPhotoCompletedEventArgs>(getphotoclient_getPhotoCompleted);

            //进行展示处理
            isLoaded = false;
            getphotoclient.getPhotoAsync(east, west, north, south);
        }

        /// <summary>
        /// 从服务器端获取图片列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void getphotoclient_getPhotoCompleted(object sender, imaginecup.ServiceReference1.getPhotoCompletedEventArgs e)
        {
            //先把所有图片列表读入
            photolist = new List<ServiceReference1.CPhoto>(e.Result);
            //在这里可以建立文件名到下标的索引
            namevalue = new Dictionary<string, int>();

            for (int i = 0; i < photolist.Count; i++)
            {
                namevalue[photolist[i].FileSuffix] = i;
            }

            photo.Children.Clear();

            refreshphotolist(0);

            curindex = 0;
            loadMainImage();

            //动画展开，1s，从右向左展开，中间图片透明度变化

            isLoaded = true;
        }

        /// <summary>
        /// 随着主图片的变化，图片列表的变化
        /// </summary>
        /// <param name="centerindex"></param>
        void refreshphotolist(int centerindex)
        {
            //删去所有照片
            photo.Children.Clear();

            //首先添加两个左右导航键
            Uri fronturi = new Uri(uriprefix + "front.JPG");
            BitmapImage frontbitimage = new BitmapImage(fronturi);
            Image frontimage = new Image();
            frontimage.Source = frontbitimage;
            frontimage.Width = 20;
            frontimage.Height = 75;
            frontimage.MouseLeftButtonUp += new MouseButtonEventHandler(frontimage_MouseLeftButtonUp);
            frontimage.SetValue(Canvas.LeftProperty, 0.0d);
            frontimage.SetValue(Canvas.TopProperty, 0.0d);
            photo.Children.Add(frontimage);

            Uri backuri = new Uri(uriprefix + "back.JPG");
            BitmapImage backbitimage = new BitmapImage(backuri);
            Image backimage = new Image();
            backimage.Source = backbitimage;
            backimage.Width = 20;
            backimage.Height = 75;
            backimage.MouseLeftButtonUp += new MouseButtonEventHandler(backimage_MouseLeftButtonUp);
            backimage.SetValue(Canvas.TopProperty, 0.0d);
            backimage.SetValue(Canvas.LeftProperty, 780.0d);
            photo.Children.Add(backimage);

            //开始载入缩略图
            int lastlong = 1;
            Storyboard sb = new Storyboard();
            sb.AutoReverse = false;
            sb.Duration = new Duration(new TimeSpan(0, 0, lastlong));

            Uri curi = new Uri(uriprefix + photolist[centerindex].FileSuffix);

            BitmapImage cbitmap = new BitmapImage(curi);
            Image ctmpimage = new Image();
            ctmpimage.Source = cbitmap;
            ctmpimage.Width = 100;
            ctmpimage.Height = 75;
            ctmpimage.Opacity = 0;

            //page-148
            ctmpimage.SetValue(Canvas.LeftProperty, Convert.ToDouble((4 - 1) * 100 + 4 * 10 + 10));
            ctmpimage.SetValue(Canvas.TopProperty, Convert.ToDouble(10));

            DoubleAnimation cda = new DoubleAnimation();
            cda.From = 0;
            cda.To = 1;

            sb.Children.Add(cda);
            Storyboard.SetTarget(cda, ctmpimage);
            Storyboard.SetTargetProperty(cda, new PropertyPath("(Opacity)"));

            cda.Duration = new Duration(new TimeSpan(0, 0, lastlong));


            photo.Children.Add(ctmpimage);

            for (int i = centerindex - 1; i >= 0 && centerindex - i < 4; i--)
            {
                Uri uri = new Uri(uriprefix + photolist[i].FileSuffix);

                BitmapImage bitmap = new BitmapImage(uri);
                Image tmpimage = new Image();
                tmpimage.Source = bitmap;
                tmpimage.Width = 100;
                tmpimage.Height = 75;
                tmpimage.Opacity = 0;

                tmpimage.MouseEnter += new MouseEventHandler(tmpimage_MouseEnter);
                tmpimage.MouseLeave += new MouseEventHandler(tmpimage_MouseLeave);
                //怎样表示点击事件？
                tmpimage.MouseLeftButtonDown += new MouseButtonEventHandler(tmpimage_MouseLeftButtonDown);
                tmpimage.MouseLeftButtonUp += new MouseButtonEventHandler(tmpimage_MouseLeftButtonUp);

                //page-148
                int tmpi = 4 + i - centerindex;
                tmpimage.SetValue(Canvas.LeftProperty, Convert.ToDouble((tmpi - 1) * 100 + tmpi * 10 + 10));
                tmpimage.SetValue(Canvas.TopProperty, Convert.ToDouble(10));

                DoubleAnimation da = new DoubleAnimation();
                da.From = 0;
                da.To = 1;

                sb.Children.Add(da);
                Storyboard.SetTarget(da, tmpimage);
                Storyboard.SetTargetProperty(da, new PropertyPath("(Opacity)"));

                da.Duration = new Duration(new TimeSpan(0, 0, lastlong));


                photo.Children.Add(tmpimage);
            }
            //补全前面的
            if (centerindex < 3)
            {
                for (int i = 1; i < 4 - centerindex; i++)
                {
                    Uri uri = new Uri(uriprefix+"b.JPG");

                    BitmapImage bitmap = new BitmapImage(uri);
                    Image tmpimage = new Image();
                    tmpimage.Source = bitmap;
                    tmpimage.Width = 100;
                    tmpimage.Height = 75;
                    tmpimage.Opacity = 0;

                    //page-148
                    tmpimage.SetValue(Canvas.LeftProperty, Convert.ToDouble((i - 1) * 100 + i * 10 + 10));
                    tmpimage.SetValue(Canvas.TopProperty, Convert.ToDouble(10));

                    DoubleAnimation da = new DoubleAnimation();
                    da.From = 0;
                    da.To = 1;

                    sb.Children.Add(da);
                    Storyboard.SetTarget(da, tmpimage);
                    Storyboard.SetTargetProperty(da, new PropertyPath("(Opacity)"));

                    da.Duration = new Duration(new TimeSpan(0, 0, lastlong));

                    photo.Children.Add(tmpimage);
                }
            }

            for (int i = centerindex + 1; i < photolist.Count && i - centerindex < 4; i++)
            {
                Uri uri = new Uri(uriprefix + photolist[i].FileSuffix);

                BitmapImage bitmap = new BitmapImage(uri);
                Image tmpimage = new Image();
                tmpimage.Source = bitmap;
                tmpimage.Width = 100;
                tmpimage.Height = 75;
                tmpimage.Opacity = 0;

                tmpimage.MouseEnter += new MouseEventHandler(tmpimage_MouseEnter);
                tmpimage.MouseLeave += new MouseEventHandler(tmpimage_MouseLeave);
                //怎样表示点击事件？
                tmpimage.MouseLeftButtonDown += new MouseButtonEventHandler(tmpimage_MouseLeftButtonDown);
                tmpimage.MouseLeftButtonUp += new MouseButtonEventHandler(tmpimage_MouseLeftButtonUp);

                //page-148
                int tmpi = 4 + i - centerindex;
                tmpimage.SetValue(Canvas.LeftProperty, Convert.ToDouble((tmpi - 1) * 100 + tmpi * 10 + 10));
                tmpimage.SetValue(Canvas.TopProperty, Convert.ToDouble(10));

                DoubleAnimation da = new DoubleAnimation();
                da.From = 0;
                da.To = 1;

                sb.Children.Add(da);
                Storyboard.SetTarget(da, tmpimage);
                Storyboard.SetTargetProperty(da, new PropertyPath("(Opacity)"));

                da.Duration = new Duration(new TimeSpan(0, 0, lastlong));

                photo.Children.Add(tmpimage);
            }
            //补全后面的
            if (photolist.Count - centerindex < 4)
            {
                for (int i = 4 + photolist.Count - centerindex; i < 8; i++)
                {
                    Uri uri = new Uri(uriprefix + "b.JPG");

                    BitmapImage bitmap = new BitmapImage(uri);
                    Image tmpimage = new Image();
                    tmpimage.Source = bitmap;
                    tmpimage.Width = 100;
                    tmpimage.Height = 75;
                    tmpimage.Opacity = 0;

                    //page-148
                    tmpimage.SetValue(Canvas.LeftProperty, Convert.ToDouble((i - 1) * 100 + i * 10 + 10));
                    tmpimage.SetValue(Canvas.TopProperty, Convert.ToDouble(10));

                    DoubleAnimation da = new DoubleAnimation();
                    da.From = 0;
                    da.To = 1;

                    sb.Children.Add(da);
                    Storyboard.SetTarget(da, tmpimage);
                    Storyboard.SetTargetProperty(da, new PropertyPath("(Opacity)"));

                    da.Duration = new Duration(new TimeSpan(0, 0, lastlong));

                    photo.Children.Add(tmpimage);
                }
            }
            LayoutRoot.Resources.Remove("storyboard");
            LayoutRoot.Resources.Add("storyboard", sb);
            sb.Begin();

            curindex = centerindex;
        }

        /// <summary>
        /// 主图片的载入，有动画
        /// </summary>
        void loadMainImage()
        {

            //图片放到grid里面
            Uri mainuri = new Uri(uriprefix + photolist[curindex].FileSuffix);
            BitmapImage mainbitmap = new BitmapImage(mainuri);
            Image maintmpimage = new Image();
            maintmpimage.Source = mainbitmap;
            maintmpimage.Width = 600;
            maintmpimage.Height = 450;
            //page-148
            maintmpimage.SetValue(Canvas.LeftProperty, 100.0d);
            maintmpimage.SetValue(Canvas.TopProperty, 100.0d);

            photo.Children.Add(maintmpimage);
            curmain = maintmpimage;
            tbktest.Text = "上传人：" + photolist[curindex].Name + " 上传时间：" + photolist[curindex].PostTime.ToString() + "纬度：" + photolist[curindex].Latitude + "经度：" + photolist[curindex].Longtitude;
        }

        /// <summary>
        /// 下一页图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void backimage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (curindex + 7 > photolist.Count - 1)
            {
                refreshphotolist(photolist.Count - 1);
            }
            else
            {
                refreshphotolist(curindex + 7);
            }
            loadMainImage();
        }

        /// <summary>
        /// 上一页图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void frontimage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (curindex > 7)
            {
                refreshphotolist(curindex - 7);
            }
            else
            {
                refreshphotolist(0);
            }
            loadMainImage();
        }

        /// <summary>
        /// 记录点击列表图片事件，如果点击释放的图片还是此图片，那么把此图片作为主图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void tmpimage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Image tmpi = (Image)e.OriginalSource;

            //如果是一样的图片不进行操作
            //todo

            if (tmpi == mousedown)
            {
                tbktest.Text = e.GetPosition(photo).X.ToString();

                //get the main photo and shrink and remove
                int i;
                for (i = 0; i < photo.Children.Count; i++)
                {
                    if ((Image)(photo.Children[i]) == curmain)
                    {
                        break;
                    }
                }
                if (i == photo.Children.Count)
                {
                    throw new Exception("image error");
                }
                else
                {
                    photo.Children.RemoveAt(i);
                }

                //get the curphoto and bigger it 
                int lastlong = 300;
                Image newimage = new Image();
                newimage.Source = ((Image)e.OriginalSource).Source;
                string tmpuri = ((BitmapImage)newimage.Source).UriSource.ToString();
                tmpuri = tmpuri.Substring(28, tmpuri.Length - 28);
                if (!namevalue.ContainsKey(tmpuri))
                {
                    throw new Exception("image error");
                }
                curindex = namevalue[tmpuri];

                refreshphotolist(curindex);

                photo.Children.Add(newimage);
                curmain = newimage;


                DoubleAnimation datop = new DoubleAnimation();
                DoubleAnimation daleft = new DoubleAnimation();
                DoubleAnimation dawidth = new DoubleAnimation();
                DoubleAnimation daheight = new DoubleAnimation();

                dawidth.From = 100;
                dawidth.To = 600;
                dawidth.Duration = new Duration(new TimeSpan(0, 0, 0, 0, lastlong));

                daheight.From = 75;
                daheight.To = 450;
                daheight.Duration = new Duration(new TimeSpan(0, 0, 0, 0, lastlong));

                datop.From = Convert.ToDouble(((Image)e.OriginalSource).GetValue(Canvas.TopProperty));
                datop.To = 100;
                datop.Duration = new Duration(new TimeSpan(0, 0, 0, 0, lastlong));

                daleft.From = Convert.ToDouble(((Image)e.OriginalSource).GetValue(Canvas.LeftProperty));
                daleft.To = 100;
                daleft.Duration = new Duration(new TimeSpan(0, 0, 0, 0, lastlong));

                Storyboard sb = new Storyboard();
                sb.Duration = new Duration(new TimeSpan(0, 0, 0, 0, lastlong));
                sb.AutoReverse = false;
                sb.Children.Add(dawidth);
                sb.Children.Add(daheight);
                sb.Children.Add(datop);
                sb.Children.Add(daleft);
                Storyboard.SetTarget(dawidth, newimage);
                Storyboard.SetTarget(daheight, newimage);
                Storyboard.SetTarget(datop, newimage);
                Storyboard.SetTarget(daleft, newimage);


                Storyboard.SetTargetProperty(dawidth, new PropertyPath("Width"));
                Storyboard.SetTargetProperty(daheight, new PropertyPath("Height"));
                Storyboard.SetTargetProperty(datop, new PropertyPath("(Canvas.Top)"));
                Storyboard.SetTargetProperty(daleft, new PropertyPath("(Canvas.Left)"));

                LayoutRoot.Resources.Remove("storyboard");
                LayoutRoot.Resources.Add("storyboard", sb);
                sb.Begin();

                //refresh the photolist
                //这个应该是重新载入了
                //refreshlist(int centerindex)
                //refreshphotolist(curindex);
            }
            tbktest.Text = "上传人：" + photolist[curindex].Name + " 上传时间：" + photolist[curindex].PostTime.ToString() + "纬度：" + photolist[curindex].Latitude + "经度：" + photolist[curindex].Longtitude;
            mousedown = null;
        }

        /// <summary>
        /// 与tmpimage_MouseLeftButtonUp相对应，如果点击释放的还是此图，那么主图片变为此图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void tmpimage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            mousedown = (Image)e.OriginalSource;
        }

        /// <summary>
        /// 鼠标离开，透明度恢复
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void tmpimage_MouseLeave(object sender, MouseEventArgs e)
        {
            ((Image)e.OriginalSource).Opacity = 1;
        }

        /// <summary>
        /// 鼠标进入，改变透明度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void tmpimage_MouseEnter(object sender, MouseEventArgs e)
        {
            ((Image)e.OriginalSource).Opacity = 0.5;
        }

    }
}
